package com.vegetable.modules.service.baseData.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.vegetable.modules.entity.baseData.InvoiceInfo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class BaiduServiceImpl {
    //设置APPID/AK/SK
    public static final String APP_ID = "119631115";
    public static final String API_KEY = "3FQuvnF0GG0EzaOR5ouButko";
    public static final String SECRET_KEY = "LMhKRm48EHN3g9wMUTySWjnzLhgq9SwR";

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().readTimeout(300, TimeUnit.SECONDS).build();

    public InvoiceInfo vatInvoice(String fileStr) throws IOException{
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        // pdf_file 可以通过 getFileContentAsBase64("C:\fakepath\dzfp_25372000000202143910_寿光市德硕果蔬专业合作社_20250725173014.pdf") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
//        RequestBody body = RequestBody.create(mediaType, "pdf_file=JVBERi0xLjcKJeLjz9MKMSAwIG9iago8PC9NZXRhZGF0YSAzIDAgUi9QYWdlcyA0IDAgUi9UeXBlIC9DYXRhbG9nPj4KZW5kb2Jq...&seal_tag=false");
        RequestBody body = RequestBody.create(mediaType, "pdf_file=" + fileStr + "&seal_tag=false");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String responseStr = response.body().string();
        String wordsResultStr = JSONObject.parseObject(responseStr).getString("words_result");
        InvoiceInfo invoiceResult = JSONObject.parseObject(wordsResultStr, InvoiceInfo.class);
        if(ObjectUtil.isNull(invoiceResult)){
            log.error("文件解析出错：{}", responseStr);
        }
        log.info("===========>{}", JSONObject.toJSONString(invoiceResult));
        String remarks = invoiceResult.getRemarks();
        Map<String, String> remarkMap = parseInvoiceRemarks(remarks);
        invoiceResult.setPurchaserBank(remarkMap.get("purchaserBank"));
        invoiceResult.setPurchaserBankAccount(remarkMap.get("purchaserAccount"));
        invoiceResult.setSellerBank(remarkMap.get("sellerBank"));
        invoiceResult.setSellerBankAccount(remarkMap.get("sellerAccount"));
        return invoiceResult;
    }

    public void financeRecognise(String fileStr) throws IOException{
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image=" + fileStr + "&seal_tag=false");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        System.out.println(response.body().string());
        log.info("===========> ｛｝");
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return JSONObject.parseObject(response.body().string()).getString("access_token");
    }


    public static Map<String, String> parseInvoiceRemarks(String remarks) {
        Map<String, String> result = new HashMap<>();
        if (remarks == null || remarks.trim().isEmpty()) {
            return result;
        }
        result = extractBankInfo(remarks);
        return result;
    }


    public static Map<String, String> extractBankInfo(String remark) {
        Map<String, String> result = new HashMap<>();

        // 预处理：移除多余空格，统一分隔符
        String normalizedRemark = remark.replaceAll("\\s+", "")
                .replaceAll("：", ":")
                .replaceAll("，", ",");

        // 使用更简单的方法：先找到所有银行和账号，然后根据上下文判断归属
        Pattern bankPattern = Pattern.compile("(购方|销方)开户银行:([^;]+)");
        Pattern accountPattern = Pattern.compile("银行账号:([^;]+)");

        Matcher bankMatcher = bankPattern.matcher(normalizedRemark);
        Matcher accountMatcher = accountPattern.matcher(normalizedRemark);

        // 收集所有银行信息
        while (bankMatcher.find()) {
            String type = bankMatcher.group(1); // "购方" 或 "销方"
            String bank = bankMatcher.group(2);

            if ("购方".equals(type)) {
                result.put("purchaserBank", bank);
            } else if ("销方".equals(type)) {
                result.put("sellerBank", bank);
            }
        }

        // 收集所有账号信息
        int index = 0;
        while (accountMatcher.find(index)) {
            String account = accountMatcher.group(1);
            int accountStart = accountMatcher.start();

            // 判断账号属于购方还是销方
            int buyerBankIndex = normalizedRemark.indexOf("购方开户银行");
            int sellerBankIndex = normalizedRemark.indexOf("销方开户银行");

            if (buyerBankIndex >= 0 && sellerBankIndex >= 0) {
                // 如果既有购方银行又有销方银行
                if (accountStart < sellerBankIndex || sellerBankIndex < buyerBankIndex) {
                    // 账号在销方银行之前或销方银行在购方银行之前
                    result.put("purchaserAccount", account);
                } else {
                    result.put("sellerAccount", account);
                }
            } else if (buyerBankIndex >= 0) {
                // 只有购方银行
                result.put("purchaserAccount", account);
            } else if (sellerBankIndex >= 0) {
                // 只有销方银行
                result.put("sellerAccount", account);
            }

            index = accountMatcher.end();
        }

        return result;
    }
}
